package com.itany.shop.service.impl;

import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.exception.CodeErrorException;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserExistException;
import com.itany.shop.exception.UserNotExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.util.MD5Util;
import com.itany.shop.util.ParameterUtil;

/**
 * @Author:石小俊
 * @Date:2022/12/15 13:38
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = (UserDao) ObjectFactory.getObject("userDao");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        // 对请求参数做一个非空保护
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password) || ParameterUtil.isNull(phone) || ParameterUtil.isNull(address)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        // 判断当前用户名是否已经被注册
        User selectUser = userDao.selectByUsername(username);
        if(selectUser != null){
            throw new UserExistException("该用户已经被注册");
        }
        // 注册用户,密码需要加密
        User user = new User(username, MD5Util.md5(password),phone,address);
        userDao.insertUser(user);
    }

    @Override
    public User login(String username, String password, String code, String image) throws RequestParameterErrorException, CodeErrorException, UserNotExistException {
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password) || ParameterUtil.isNull(code) || ParameterUtil.isNull(image)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        // 校验验证码
        if(!code.equals(image)){
            throw new CodeErrorException("验证码不正确");
        }
        // 根据用户名与密码查询,密码需要加密
        User user = userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));
        if(null == user){
            throw new UserNotExistException("用户名或密码错误");
        }
        return user;
    }
}
